package com.tanhua.dubbo.api;

import com.tan.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiimpl implements FriendApi{
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public void saveFriend(Long currentUserId, Long userId) {
        Criteria criteria = Criteria.where("userId").is(currentUserId).and("friendId").is(userId);
        if (!mongoTemplate.exists(Query.query(criteria),Friend.class)){
            Friend friend = new Friend();
            friend.setUserId(currentUserId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        Criteria criteria1 = Criteria.where("userId").is(userId).and("friendId").is(currentUserId);
        if (!mongoTemplate.exists(Query.query(criteria1),Friend.class)){
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(currentUserId);
            mongoTemplate.save(friend1);
        }



    }

    @Override
    public List<Friend> searchFriends(Long userId) {
        Criteria criteria = Criteria.where("friendId").is(userId);
        Query query = Query.query(criteria);
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        return friends;
    }
}
